package com.matrix.draft.playlucene.day1;

import com.matrix.draft.playlucene.day1.dao.SkuDao;
import com.matrix.draft.playlucene.day1.dao.impl.SkuDaoImpl;
import com.matrix.draft.playlucene.pojo.Sku;
import lombok.SneakyThrows;
import org.apache.lucene.document.*;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.wltea.analyzer.lucene.IKAnalyzer;

import java.nio.file.Paths;
import java.util.LinkedList;
import java.util.List;
import java.util.function.Consumer;

public class SimpleLucene {

    public static void main(String[] args) throws Exception {

        // 0. 准备数据
        SkuDao skuDao = new SkuDaoImpl();
        List<Sku> skus = skuDao.list();

        // 1. 准备Document对象
        List<Document> documents = new LinkedList<>();
        for (Sku sku : skus) {
            Document doc = new Document();
            doc.add(new StringField("id", sku.getId(), Field.Store.YES));
            doc.add(new TextField("name", sku.getName(), Field.Store.YES));
            doc.add(new IntPoint("price", sku.getPrice()));
            doc.add(new StoredField("price", sku.getPrice()));
            doc.add(new StoredField("image", sku.getImage()));
            doc.add(new StringField("categoryName", sku.getCategoryName(), Field.Store.YES));
            doc.add(new TextField("brandName", sku.getBrandName(), Field.Store.YES));
            documents.add(doc);
        }

        // 2. 创建Directory对象(表示索引文件存放的位置)
        Directory indexDir = FSDirectory.open(Paths.get("D:\\res\\bigdata\\index"));

        // 3. 创建IndexWriter(向Directory中写入索引信息)
        IndexWriterConfig indexConfig = new IndexWriterConfig(new IKAnalyzer());
        indexConfig.setMaxBufferedDocs(300000);
        IndexWriter writer = new IndexWriter(indexDir, indexConfig);
        writer.forceMerge(100); // 最大多少个文档合成一segment, 设大索引快查询慢, 设小索引慢查询快
        documents.forEach(new Consumer<Document>() {
            @Override
            @SneakyThrows
            public void accept(Document doc) {
                writer.addDocument(doc);
            }
        });
        writer.commit();
        writer.flush();
        writer.close();

    }

}
